<template>
    <div>
        <div class="top">
            <el-button type="primary" @click="addgoods">新建</el-button>
            <el-button type="primary" @click="refresh">刷新</el-button>
        </div>
        <!-- 商品表格 -->
        <div style="height: 70vh;">
            <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" class="my-4"
                style="width: 100%;height:100%;" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="goodsname" label="商品名" width="180" />
                <el-table-column label="商品封面图" width="180">
                    <template #default="scope">
                        <img :src="scope.row.goodsimg[0]" alt="" class="w-27">
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="120" />
                <el-table-column prop="sales" label="销量" width="120" />
                <el-table-column prop="tag" label="是否上线" width="100" :filters="filters" :filter-method="filterTag"
                    filter-placement="bottom-end">
                    <template #default="scope">
                        <el-tag :type="scope.row.tag === '下架' ? 'danger' : 'success'" disable-transitions>{{
                            scope.row.tag
                            }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="success" @click="buy(scope)">购买</el-button>
                        <el-button type="primary" @click="editrow(scope)">编辑</el-button>
                        <!-- <el-button type="danger" @click="deleterow(scope)">删除</el-button> -->
                        <el-popconfirm title="确定删除吗?" icon="null" confirmButtonType="danger" confirmButtonText="确定"
                            cancelButtonText="取消" @confirm="deleterow(scope)">
                            <template #reference>
                                <el-button type="danger" v-loading.fullscreen.lock="fullscreenLoading">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 页码 -->
            <div class="block">
                <el-pagination layout="prev, pager, next" pager-count="5" :page-count="totalpage"
                    @current-change="changepage" @next-click="nextpage" @prev-click="prevpage"> </el-pagination>
            </div>
            <div>
                <el-button type="primary" @click="deleteselect"
                    v-loading.fullscreen.lock="fullscreenLoading">删除选择</el-button>
            </div>
        </div>
        <!-- 新建弹出框 -->
        <el-dialog title="新建商品" v-model="dialogVisible" width="40%" :before-close="handleClose">
            <el-form label-position="top" :model="rrgoods">
                <el-form-item label="商品名称">
                    <el-input v-model="rrgoods.name" clearable></el-input>
                </el-form-item>
                <el-form-item label="商品图片">
                    <!-- <el-input v-model="rrgoods.img" clearable></el-input> -->
                    <el-upload action="" :http-request="UploadImage" multiple :limit="1" name="files"
                        accept="image/jpeg,image/png" list-type="picture-card" :on-preview="addhandlePictureCardPreview"
                        :on-remove="handleRemove" :before-upload="onBeforeUpload">
                        <el-icon :size="size" :color="color">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog style="width: 400px; heigth: 400px" v-model="pohots">
                        <img style="width: 100%;" :src="rrgoods.img" alt="" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品价格">
                    <el-input v-model="rrgoods.price" clearable></el-input>
                </el-form-item>
                <el-form-item label="是否上线">
                    <el-select v-model="rrgoods.tag" placeholder="请选择">
                        <el-option v-for="item in tagoptions" :key="item.value" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="sureadd" v-loading.fullscreen.lock="fullscreenLoading">确
                        定</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 编辑弹出框 -->
        <el-dialog title="编辑商品" v-model="updateVisible" width="40%">
            <el-form label-position="top" :model="rrgoods">
                <el-form-item label="商品名称">
                    <el-input v-model="updaterrgoods.name" clearable></el-input>
                </el-form-item>
                <el-form-item label="商品封面图">
                    <!-- <el-input v-model="updaterrgoods.img" clearable></el-input> -->
                    <el-upload action="" v-model:file-list="fileList" :http-request="EitdImage" multiple name="files"
                        accept="image/jpeg,image/png" list-type="picture-card" :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove" :before-upload="onBeforeUpload">
                        <el-icon :size="size" :color="color">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <!-- <el-dialog style="width: 400px; heigth: 400px" v-model="updatePohots">
                        <img style="width: 100%;" :src="updaterrgoods.img" alt="" />
                    </el-dialog> -->
                </el-form-item>
                <el-form-item label="商品价格">
                    <el-input v-model="updaterrgoods.price" clearable></el-input>
                </el-form-item>
                <el-form-item label="是否上线">
                    <el-select v-model="updaterrgoods.tag" placeholder="请选择">
                        <el-option v-for="item in tagoptions" :key="item.value" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="updateVisible = false">取 消</el-button>
                    <el-button type="primary" @click="sureupdate" v-loading.fullscreen.lock="fullscreenLoading">确
                        定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { srrgoodsforpage, deleterrgoods, addrrgoods, updategoods, deleteMorerrgoods, searchsalescount, buygoods } from '../../../../api/api'
import Format from '../../../../api/uploadimg'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'



let dialogVisible = ref(false)  //新建弹出框
let pohots = ref(false)  //上传图片后显示
let updatePohots = ref(false)
let dialogImageUrl = ref('')  //上传后显示的图片数组
let updateImageUrl = ref('')   //编辑上传后显示的图片数组
let fileObj = ref([])    //上传的图片文件
let updateVisible = ref(false)  //编辑弹出框
let deleteArrs = ref([])   //删除选中的id
let filters = ref([{ text: '上线', value: '上线' }, { text: '下架', value: '下架' }])
let fullscreenLoading = ref(false)  //加载显示
let rrgoods = ref({ name: '', img: [], price: '', tag: '' })  //新建商品参数
let updaterrgoods = ref({ id: '', name: '', img: [], price: '', tag: '' })  //编辑商品参数
let fileList = ref([])
let tableData = ref([])   //商品列表
let totalpage = ref(1)  //表格页数
let pageNum = ref(1)
let pageSize = ref(5)
let currentpage = ref(1)
let tagoptions = ref([
    {
        value: '1',
        label: '上线',
    },
    {
        value: '2',
        label: '下架',
    }
])


//查询所有数据
const gettabledata = (refresh) => {
    fullscreenLoading.value = true
    let data = {
        pageNum: Number(pageNum.value),
        pageSize: Number(pageSize.value)
    }
    // console.log(data);
    srrgoodsforpage(data).then(res => {
        if (res.data.data.code == 200) {
            tableData.value = res.data.data.rrgoods
            totalpage.value = Number(res.data.data.pageCount)
            currentpage.value = res.data.data.pageNumber
            searchsalescount().then(res2 => {
                console.log(res2);
            })
            if (refresh) {
                ElMessage.success("刷新成功")
            }
        } else {
            ElMessage.error(res.data.data.msg)
            if (refresh) {
                ElMessage.error("刷新失败")
            }
        }
        fullscreenLoading.value = false
    })

}
gettabledata()



//点击上一页
const prevpage = (e) => {
    pageNum.value = e
    gettabledata()
}

//点击下一页
const nextpage = (e) => {
    pageNum.value = e
    gettabledata()
}

//改变页码
const changepage = (e) => {
    pageNum.value = e
    gettabledata()
}

//点击新建
const addgoods = () => {
    dialogVisible.value = true
}
//点击新建框X
const handleClose = () => {
    dialogVisible.value = false
}
//点击确认新建
const sureadd = () => {
    fullscreenLoading.value = true
    let data = {
        goodsname: rrgoods.value.name,
        goodsimg: rrgoods.value.img,
        price: rrgoods.value.price,
        tag: rrgoods.value.tag
    }
    addrrgoods(data).then(res => {
        if (res.data.data.code == 200) {
            ElMessage.success(res.data.data.msg)
            gettabledata()
        } else {
            ElMessage.error(res.data.data.msg)
        }
        dialogVisible.value = false
        fullscreenLoading.value = false
    })
}
//刷新
const refresh = () => {
    let refresh = ref(true)
    gettabledata(refresh)
}

//选中的数组
const handleSelectionChange = (val) => {
    if (val.length > 0) {
        val.map(item => {
            deleteArrs.value.push(item.id)
        })
    } else {
        deleteArrs.value = []
    }
}

//点击删除上传的图片
const handleRemove = (file, fileList) => {
    updaterrgoods.value.img = []
    fileList.forEach(item => {
        updaterrgoods.value.img.push(item.url)
    })
}

//确认上传图片显示上传的图片
const addhandlePictureCardPreview = (file) => {
    console.log(file);
    dialogImageUrl.value = file.url
    pohots.value = true
}

//上传前的操作
const onBeforeUpload = (file) => {
    const isIMAGE = file.type === 'image/jpeg' || 'image/png';
    const isLt1M = file.size / 1024 / 1024 < 5;

    if (!isIMAGE) {
        ElMessage.error('上传文件只能是图片格式!');
    }
    if (!isLt1M) {
        ElMessage.error('上传文件大小不能超过 5MB!');
    }
    return isIMAGE && isLt1M;
}

//点击上传文件
const UploadImage = (files) => {
    fileObj.value = files.file;
    // 创建文件流
    let formData = new FormData();
    formData.append('files', fileObj.value);
    // Format封装在utilsg工具函数中
    Format.fileUploader(formData, '/uploading').then(res => {
        if (res.data.data.code == 200) {
            ElMessage.success("上传成功!")
            rrgoods.value.img = res.data.data.imgurl
        }
    })
}


//点击编辑
const editrow = (scope) => {
    updateVisible.value = true
    fileList.value = []
    if (tableData.value[scope.$index].goodsimg.length > 0) {
        tableData.value[scope.$index].goodsimg.forEach((item, index) => {
            fileList.value.push({
                name: index,
                url: item
            })
            updaterrgoods.value.img.push(item)
        });
    }
    
    updaterrgoods.value.id = tableData.value[scope.$index].id
    updaterrgoods.value.name = tableData.value[scope.$index].goodsname
    updaterrgoods.value.price = tableData.value[scope.$index].price
    updaterrgoods.value.tag = tableData.value[scope.$index].tag
}

//编辑确认上传后
const handlePictureCardPreview = (file) => {
    console.log(file);
    updateImageUrl.value = file.url
    updatePohots.value = true
}

//编辑上传图片
const EitdImage = (files) => {
    fileObj.value = files.file;
    // 创建文件流
    let formData = new FormData();
    formData.append('files', fileObj.value);
    // Format封装在utilsg工具函数中
    Format.fileUploader(formData, '/uploading').then(res => {
        if (res.data.data.code == 200) {
            ElMessage.success("上传成功!")
            updaterrgoods.value.img.push(res.data.data.imgurl)
        }
    })
}

//点击编辑确认
const sureupdate = () => {
    fullscreenLoading.value = true
    console.log(updaterrgoods.value.img, 'updaterrgoods.value.img');

    let data = {
        goodsname: updaterrgoods.value.name,
        goodsimg: updaterrgoods.value.img.join(','),
        price: updaterrgoods.value.price,
        tag: updaterrgoods.value.tag,
        id: updaterrgoods.value.id
    }
    console.log(data);
    updategoods(data).then(res => {
        if (res.data.data.code == 200) {
            ElMessage.success(res.data.data.msg)
            gettabledata()
        }
        else {
            ElMessage.error(res.data.data.msg)
        }
        fullscreenLoading.value = false
        updateVisible.value = false

    })

}

//根据标签过滤数组
const filterTag = function (value, row) {
    return row.tag === value
}

//点击购买
const buy = function (scope) {
    let data = {
        id: tableData.value[scope.$index].id
    }
    buygoods(data).then(res => {
        if (res.data.data.code == 200) {
            ElMessage.success(res.data.data.msg)
            gettabledata()
        }
        else {
            ElMessage.error(res.data.data.msg)
        }
    })

}


//点击删除
const deleterow = (scope) => {
    fullscreenLoading.value = true
    let data = {
        id: tableData.value[scope.$index].id
    }
    deleterrgoods(data).then(res => {
        if (res.data.data.code == 200) {
            ElMessage.success(res.data.data.msg)
            gettabledata()
        }
        else {
            ElMessage.error(res.data.data.msg)
        }
        fullscreenLoading.value = false
    })
}
//点击删除选中
const deleteselect = () => {
    if (deleteArrs.value.length > 0) {
        ElMessageBox.confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            let data = deleteArrs.value
            deleteMorerrgoods(data).then(res => {
                if (res.data.data.code == 200) {
                    ElMessage.success(res.data.data.msg)
                    deleteArrs.value = []
                    getemploylist()
                }
                else {
                    ElMessage.error(res.data.data.msg)
                }
            })
        }).catch(() => {

        })
    } else {
        ElMessage.error('请勾选需要删除的员工信息')
    }
}


</script>

<style>
.el-upload--picture-card {
    background-color: #fff !important;
}
</style>